package com.wangdao.mall.filter;

import com.google.gson.Gson;
import com.wangdao.mall.model.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author:HaiyangTian
 * @Description:
 * @Date: Created in 16:28 2020/4/29
 * @Modified By:
 */
@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //设置字符集
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //将试探请求options转化为正常响应请求
        //这个地址在不同的环境也是要变的
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");
/*        String method = request.getMethod();
        //因为options试探请求的session会发生变化
        //只有转化成对应的响应请求session才不会变
        //所以直接放行就可以了
        if (!"OPTIONS".equals(method)) {
            String uri = request.getRequestURI();
            if (auth(uri)){
                HttpSession session = request.getSession();
                String email = (String) session.getAttribute("email");
                //没有email说明没有登录，进行拦截
                if (email == null) {
                    Result result = new Result();
                    result.setCode(10000);
                    result.setMessage("您还没有登录，请登录后再访问");
                    response.getWriter().println(new Gson().toJson(result));
                    return;
                }
            }
        }*/
        chain.doFilter(request, response);
    }

    /**
     * 除了登陆外，都应该设置拦截，只要没登陆就不予访问
     * @param uri
     * @return
     */
    private boolean auth(String uri) {
        if ("/api/admin/admin/login".equals(uri)){
            return false;
        }
        return true;
    }

    public void init(FilterConfig config) throws ServletException {

    }
}
